package cn.fxzhang.leetcode.no02;

/**
 * 208. 实现 Trie (前缀树)
 *
 * 类型：字典树
 * 时间复杂度：初始化为 O(1)，其余操作为 O(|S|)，其中 |S| 是每次插入或查询的字符串的长度
 * 空间复杂度：O(∣T∣⋅Σ)，其中 |T|为所有插入字符串的长度之和，Σ 为字符集的大小，本题Σ=26
 *
 * 提交记录(1/1)：
 * 执行用时: 54 ms, 击败了22.36%
 * 内存消耗: 48 MB, 击败了60.25%
 *
 * 【中等】通过次数108,311提交次数151,651
 * @author 张晓帆
 * @date 2021/3/30
 */
public class Trie {

    private Trie[] children;
    private boolean isLeaf;


    /** Initialize your data structure here. */
    public Trie() {
        children = new Trie[26];
        isLeaf = false;
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie t = this;
        for (int i=0; i<word.length(); i++){
            int j = word.charAt(i) - 'a';
            if (t.children[j] == null) {
                t.children[j] = new Trie();
            }
            t = t.children[j];
        }
        t.isLeaf = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie t = this;
        for (int i=0; i<word.length(); i++){
            int j = word.charAt(i) - 'a';
            if (t.children[j]==null){
                return false;
            }
            t = t.children[j];
        }
        return t.isLeaf;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie t = this;
        for (int i=0; i<prefix.length(); i++){
            int j = prefix.charAt(i) - 'a';
            if (t.children[j]==null){
                return false;
            }
            t = t.children[j];
        }
        return true;
    }
}
